/*
 * simple promise
 * The promise constructor accepts a function with 2 arguments, resolve (function) and reject (
 * function). resolve is called upon success, and reject is called upon error.
 * To use a promise, use either then or catch. Use then for resolve and catch for reject
 */
const simplePromiseGetBearPromise = () => {
  require('path');
  return new Promise((resolve, reject) => {
    require('fs').readFile(__dirname + '/../resources/bears.txt', 'utf-8', (err, text) => {
      if (err) {
        reject(err);
      } else {
        resolve(text);
      }
    })
  });
};
const simplePromise = () => {
  simplePromiseGetBearPromise().then(text => {
    const lines = text.split('\n');
    // need to add -1 because lines.pop() will always be ''
    const randomLine = lines[Math.floor(Math.random() * (lines.length - 1))];
    console.log(randomLine);
  }).catch(error => console.log(error.message));
};
simplePromise();
simplePromise();
simplePromise();

/*
 * promise chain
 * promises can be chained with the .then().then().then() pattern
 */
var FrenchContract = function(firstWord, secondWord) {
  this.firstWord = firstWord;
  this.secondWord = secondWord;
  this.fileName = 'contract';
};
FrenchContract.prototype.getFilePromise = function(fileId) {
  this.fileId = fileId;
  new Promise((resolve, reject) => {
    require('fs').readFile(
      `./resources/${this.fileName}-${fileId}.txt`,
      'utf-8',
      (err, fileLines) => {
        if (err) {
          console.log(err.message);
          reject(err);
        } else {
          const lines = fileLines.split('\n');
          lines.pop();
          resolve(lines);
        }
      }
    );
  }).then(this.then2.bind(this));
};
// nothing fancy, check if the word pair is found in the resource file
FrenchContract.prototype.checkMatch = function(fileLines) {
  const trimmedLines = fileLines.map(line => line
    .trim()
    .split(/[+=]/)
  ).map(line => {
    return {
      firstWord: line[0].trim(),
      secondWord: line[1].trim(),
      contractedWord: line[2].trim()
    }
  });
  // console.log('trimmedLines', trimmedLines);
  const match = trimmedLines.find(
    line => (line.firstWord === this.firstWord && line.secondWord === this.secondWord)
  );
  if (match) {
    const shouldContract = this.fileName === 'contract';
    return {
      matched: true,
      shouldContract,
      contractedWord: match.contractedWord,
    }
  } else {
    return {
      matched: false,
    }
  }
};
FrenchContract.prototype.getResultString = function(match) {
  if (match.shouldContract) {
    return `${this.firstWord} + ${this.secondWord} should be contracted to:
    ${match.contractedWord}`;
  } else {
    return `${this.firstWord} + ${this.secondWord} should not be contracted`;
  }
};
FrenchContract.prototype.then2 = function(fileLines) {
  var checkMatch = this.checkMatch.bind(this);
  const match = checkMatch(fileLines);
  if (match.matched) {
    console.log(this.getResultString(match));
  } else {
    var gfp = this.getFilePromise.bind(this);
    gfp(this.fileId + 1);
  }
};
const frenchContract = (firstWord, secondWord) => {
  const result = {};
  var contract = new FrenchContract(firstWord, secondWord);
  contract.getFilePromise(1);
};
frenchContract('ce', 'est2');
